/**
 * Created by zhangyunqi on 2017/6/11.
 */
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;

public class Chain {
    static final int NPREF = 2; //前缀个数

    static final String NOWORD = "\n"; //英语单词不再重复

    Map<Prefix,List<String>> stateTable = new HashMap<Prefix,List<String>>();

    Prefix prefix = new Prefix (NPREF,NOWORD);//刚开始的前缀

    Random random = new Random();


    public void build(InputStream in) throws Exception {
        Scanner scanner = new Scanner(in);

        while(scanner.hasNext()){
            add(scanner.next());
        }
        add(NOWORD);
    }

    private void add(String word) {
        List<String> suf = stateTable.get(prefix);
        if(suf == null){
            suf = new ArrayList<String>();
            stateTable.put(new Prefix(prefix),suf);
        }
        suf.add(word);
        prefix.pref.remove(0);
        prefix.pref.add(word);
    }


    public void generate(int nwords) throws IOException {
        FileWriter fw = new FileWriter("C:\\Users\\think\\Desktop\\qq.txt");//生成的文章储存在qq.txt中
        prefix = new Prefix(NPREF,NOWORD);
        for(int i=0; i<nwords; i++){
            List<String> suf = stateTable.get(prefix);
            int r = Math.abs(random.nextInt() % suf.size());
            String word = suf.get(r);
            if(word.equals(NOWORD)){
                break;
            }
            System.out.print(word+" ");
            if (word.equals(".")){
                fw.write("\n");
            }
            else
                fw.write(word+" ");


            prefix.pref.remove(0);
            prefix.pref.add(word);
        }
        fw.close();
    }

}
